<template>
  <el-drawer
    :title="title"
    :modal-append-to-body="false"
    :modal="false"
    size="auto"
    :wrapperClosable="false"
    :visible.sync="isShowCart"
    direction="btt">
    <el-form :inline="true" size="small" label-width="84px">
        <el-form-item label="日期范围：">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            popper-class="drawer-date-range"
            @change="getList">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
        <el-alert type="warning" title="选择的日期范围不能超过 7 天" show-icon :closable="false" style="padding:0 15px"/>
        </el-form-item>

      </el-form>
      <v-chart :options="options" :autoresize="true" style="height:240px;width:100%;"></v-chart>
  </el-drawer>
</template>
<script>
import {types,legendColors} from '../config';
export default {
  props:{
    currentDate:{
      type: String,
    },
    selData:{
      type: Object
    }
  },
  data(){
    return {
      isShowCart: false,
      title: null,
      dateRange:[],
      options: {},
      list:[],
      stationCode: null
    }
  },
  methods:{
    init(data){
      this.isShowCart = true;
      this.title = data.city + '市'+ data.station_name + '站实况气象';
      this.stationCode = data.station_code;
      let arr = [];
      arr.push(this.$moment(data.update_time).add(-1, 'd').format('YYYY-MM-DD HH:mm:ss'));
      arr.push(this.$moment(data.update_time).format('YYYY-MM-DD HH:mm:ss'));
      this.dateRange = arr;
      this.getList();
    },
    getList(){
      if(!this.dateRange){
        this.$message.warning('请选择日期');
        return;
      }else{
        let start = this.dateRange[0].split(' ')[0];
        let end = this.dateRange[1].split(' ')[0];
        var diff = this.$moment(end).diff(start, 'days');
        if(diff > 7){
          this.$message.warning('选择的日期范围不能超过 7 天');
          return;
        }
      }

      let params = {
        station_code: this.stationCode,
        start: this.dateRange[0],
        end: this.dateRange[1]
      };
      this.$request('get', '/air/nmc/station', params, (data,msg) => {
        this.list = data.reverse();
        this.initOption();
      });
    },
    initOption() {
      const rains = this.list.map(i => i.rain1h);
      const temperatures = this.list.map(i => i.temperature);
      const humiditys = this.list.map(i => i.humidity);
      const pressures = this.list.map(i => i.pressure);
      const windbarbs = [];
      const icons = legendColors.wind_speed.icons;
      const markLineData = [];
      this.list.forEach((i, idx) => {
        let url = icons[0].url;
        if (i.wind_speed > 2) {
          url = icons[1].url;
        }
        if (i.wind_speed > 4) {
          url = icons[2].url;
        }
        if (i.wind_speed > 6) {
          url = icons[3].url;
        }
        if (i.wind_speed > 8) {
          url = icons[4].url;
        }
        if (i.wind_speed > 10) {
          url = icons[5].url;
        }
        if (i.wind_speed > 12) {
          url = icons[6].url;
        }
        if (i.wind_speed > 14) {
          url = icons[7].url;
        }
        if (i.wind_speed > 16) {
          url = icons[8].url;
        }
        if (i.wind_speed > 18) {
          url = icons[9].url;
        }
        if (i.wind_speed > 20) {
          url = icons[10].url;
        }
        if (i.wind_speed > 22) {
          url = icons[11].url;
        }
        windbarbs.push({
          value: 0,
          symbol: 'image://' + url,
          symbolSize: [25, 25],
          symbolRotate: -i.wind_direction,
          symbolOffset: [0, '180%']
        });
        const hour = this.$moment(i.update_time).format('HH');
        if (hour === '00') {
          markLineData.push({
            name: 'X' + idx,
            xAxis: idx
          });
        }
      });
      const colorList = ['#585EAA', '#F78622', '#10F81A', '#09B3F1'];
      const options = {
        tooltip: {
          show: true,
          confine: true,
          formatter: (params) => {
            if (params.seriesIndex !== 4) {
              const str = params.seriesName.match(/\（(.+?)\）/g);
              const str0 = str[0].replace('（', '');
              const unit = str0.replace('）', '');
              const dt = this.$moment(params.name).format('YYYY-MM-DD HH:00');
              const name = params.seriesName.replace(str[0], '');
              return dt + '<br/>' + params.marker + name + '：' + params.data + unit;
            }
            const val = this.list[params.dataIndex].wind_speed;
            const dt = this.$moment(params.name).format('YYYY-MM-DD HH:00');
            return dt + '<br/>' + params.marker + '风速' + '：' + val + 'm/s';
          }
        },
        grid: {
          top: 40,
          right: 60,
          left: 30,
          bottom: 55,
          containLabel: true
        },
        legend: {
          data: [{name: '降水（mm）', icon: 'circle'}, '温度（℃）', '相对湿度（%）', '气压（hPa）']
        },
        xAxis: {
          type: 'category',
          data: this.list.map(i => i.update_time),
          interval: 0,
          axisLabel: {
            rotate: 45,
            formatter: (params) => {
              return this.$moment(params).format('HH时')
            }
          }
        },
        yAxis: [
          {
            position: 'right',
            type: 'value',
            name: '降水',
            // nameGap: 30,
            // nameLocation: 'middle',
            splitNumber: 2,
            minInterval: 0.1,
            min: Math.floor(Math.min(...rains)),
            max: Math.ceil(Math.max(...rains)),
            interval: +((Math.ceil(Math.max(...rains)) - Math.floor(Math.min(...rains))) / 2).toFixed(1),
            axisTick: {
              show: false,
            },
            splitLine: {
              show: true,
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: colorList[2]
              }
            },
            axisLabel: {
              formatter: (value) => {
                const str = value.toString();
                return str.indexOf('.') > -1 ? value.toFixed(1) + 'mm' : value + 'mm';
              }
            }
          },
          {
            position: 'left',
            type: 'value',
            name: '温度',
            splitNumber: 2,
            minInterval: 0.1,
            min: Math.floor(Math.min(...temperatures) - 2),
            max: Math.ceil(Math.max(...temperatures) + 2),
            interval: +((Math.ceil(Math.max(...temperatures) + 2) - Math.floor(Math.min(...temperatures) - 2)) / 2).toFixed(1),
            axisTick: {
              show: false,
            },
            splitLine: {
              show: true,
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: colorList[1]
              }
            },
            axisLabel: {
              formatter: (value) => {
                const str = value.toString();
                return str.indexOf('.') > -1 ? value.toFixed(1) + '℃' : value + '℃';
              }
              // formatter: '{value}℃'
            }
          },
          {
            position: 'right',
            offset: 50,
            type: 'value',
            name: '相对湿度',
            // nameGap: 30,
            // nameLocation: 'middle',
            splitNumber: 2,
            minInterval: 0.1,
            min: Math.floor(Math.min(...humiditys) - 2),
            max: Math.ceil(Math.max(...humiditys) + 2),
            interval: +((Math.ceil(Math.max(...humiditys) + 2) - Math.floor(Math.min(...humiditys) - 2)) / 2).toFixed(1),
            axisTick: {
              show: false,
            },
            splitLine: {
              show: true,
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: colorList[3]
              }
            },
            axisLabel: {
              formatter: (value) => {
                const str = value.toString();
                return str.indexOf('.') > -1 ? value.toFixed(1) + '%' : value + '%';
              }
              // formatter: '{value}%'
            }
          },
          {
            position: 'left',
            offset: 50,
            type: 'value',
            name: '气压',
            // nameGap: 40,
            // nameLocation: 'middle',
            splitNumber: 2,
            minInterval: 0.1,
            min: Math.floor(Math.min(...pressures) - 2),
            max: Math.ceil(Math.max(...pressures) + 2),
            interval: +((Math.ceil(Math.max(...pressures) + 2) - Math.floor(Math.min(...pressures) - 2)) / 2).toFixed(1),
            axisLine: {
              show: true,
              lineStyle: {
                color: colorList[0]
              }
            },
            axisTick: {
              show: false,
            },
            splitLine: {
              show: false,
            },
            axisLabel: {
              // formatter: '{value}hPa'
              formatter: (value) => {
                const str = value.toString();
                return str.indexOf('.') > -1 ? value.toFixed(1) + 'hPa' : value + 'hPa';
              }
            }
          },
          // {
          //   show: false,
          //   type: 'value',
          //   name: '风速',
          //   min: -30,
          // },
        ],
        series: [
          {
            type: 'bar',
            name: '降水（mm）',
            data: rains,
            yAxisIndex: 0,
            lineStyle: {
              color: colorList[2],
            },
            itemStyle: {
              color: colorList[2]
            }
          },
          {
            type: 'line',
            name: '温度（℃）',
            data: temperatures,
            yAxisIndex: 1,
            symbol: 'circle',
            symbolSize: 8,
            showAllSymbol: true,
            lineStyle: {
              color: colorList[1],
            },
            itemStyle: {
              color: colorList[1],
            }
          },
          {
            type: 'line',
            name: '相对湿度（%）',
            data: humiditys,
            yAxisIndex: 2,
            symbol: 'rect',
            symbolSize: 6,
            showAllSymbol: true,
            lineStyle: {
              color: colorList[3],
            },
            itemStyle: {
              color: colorList[3],
            },
          },
          {
            type: 'line',
            name: '气压（hPa）',
            data: pressures,
            yAxisIndex: 3,
            symbol: 'diamond',
            symbolSize: 10,
            showAllSymbol: true,
            lineStyle: {
              color: colorList[0],
            },
            itemStyle: {
              color: colorList[0],
            }
          },
          {
            name: '风羽图',
            type: 'line',
            data: windbarbs,
            showAllSymbol: true,
            lineStyle: {
              width: 0,
            },
            itemStyle: {
              color: '#000'
            }
          }
        ],
        dataZoom: [
          {
            show: true,
            height: 16,
            xAxisIndex: [0],
            bottom: 16,
            start: 0,
            end: 100,
            handleIcon: 'path://M306.1,413c0,2.2-1.8,4-4,4h-59.8c-2.2,0-4-1.8-4-4V200.8c0-2.2,1.8-4,4-4h59.8c2.2,0,4,1.8,4,4V413z',
            handleSize: '110%',
            // handleStyle: {
            //   color: '#5B3AAE',
            // },
            // textStyle: {
            //   color: 'rgba(204,187,225,0.5)',
            // },
            // fillerColor: 'rgba(67,55,160,0.4)',
            // borderColor: 'rgba(204,187,225,0.5)',
          }, {
            type: 'inside',
            show: true,
            height: 10,
            start: 1,
            end: 100
          }
        ],
      };
      options.series.forEach((s) => {
        s.markLine = {
          silent: true,
          label: {
            show: false,
          },
          lineStyle: {
            color: '#007500',
            type: 'solid',
            width: 2
          },
          symbol: false,
          data: markLineData
        }
      });
      this.options = options;
    }
  }
}

</script>